import os
from multiprocessing import Manager, Lock

import joblib
from xbase_util.common_util import check_path

from src.bean.model_database_enum import ModelDatabaseEnum
from src.constant import project_root_path


class ConfigManager:
    """
    数据库和配置
    """

    def __init__(self):
        self.database_path = os.path.join(project_root_path, "data", "database.json")
        self.manager = Manager()
        self.config = self.manager.dict()
        self.lock = Lock()
        if os.path.exists(self.database_path):
            self.database = joblib.load(self.database_path)
        else:
            self.database = []

    def get_new_id(self):
        return max([item[ModelDatabaseEnum.id.value] for item in self.database], default=0) + 1

    def get_model_list(self):
        return self.database

    def db_save(self):
        joblib.dump(self.database, check_path(self.database_path))

    def set_config(self, key, value):
        """设置配置项"""
        with self.lock:
            self.config[key] = value

    def get_config(self, key, default=None):
        """获取配置项"""
        with self.lock:
            return self.config.get(key, default)

    def remove_model(self, model):
        model_path = model[ModelDatabaseEnum.model_path.value]
        if os.path.exists(model_path):
            os.remove(model_path)
        self.database.remove(model)
